<template>
    <div class="prop-data-form-define">
        <el-form ref="form" label-width="80px" size="mini" style="background: #FAFAFA;padding: 10px 0;border-radius: 2px;">
            <el-form-item label="引用页面">
                <el-tag v-if="page?.page_code" size="medium" style="margin-right: 10px;">
                    {{page.page_name}}
                </el-tag>
                <el-button type="primary" plain @click="showSourceWin()">选择引用页面</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script setup>
import {ref, reactive, computed, watch, onMounted, toRefs} from 'vue'
import {$WinPages} from "@jzl/comps-mg";
import {api} from "@jzl/api";

// 定义 props
const props = defineProps({
  item: {
    type: Object,
    required: true
  },
  pages: {
    type: Array,
    default: () => []
  },
  currentPageItems: {
    type: Array,
    default: () => []
  }
})

// 定义 emits
const emit = defineEmits(['update:item'])

// 状态
const state = reactive({
  page: {}
})

const { page } = toRefs(state)

// 方法实现
const init = () => {
  const dataDync = _.get(props.item, 'data_dync')
  if (dataDync) {
    if (!dataDync.page_code) {
      dataDync.page_code = ''
      // 创建新的对象以保持响应性
      const newItem = { ...props.item }
      newItem.data_dync = { ...newItem.data_dync, page_code: '' }
      emit('update:item', newItem)
    }
  }
}

const loadFormData = async () => {
  state.form = null

  let _page = _.get(props.item, '_page', {})

  if (_page && _page.page_code === _.get(props.item, 'data_dync.page_code')) {
    // 页面代码未变化，无需重新加载
  } else if (_.get(props.item, 'data_dync.page_code')) {
    try {
      _page = await api.page.getPageByCode(_.get(props.item, 'data_dync.page_code'))
    } catch (error) {
      console.error('Failed to load page:', error)
    }
  }

  // 创建新的 item 对象以保持响应性
  const newItem = { ...props.item }
  newItem._page = _page

  emit('update:item', newItem)
  state.page = _page
}

const showSourceWin = () => {
  $WinPages({
    onConfirm: async (info) => {
      const page_code = _.get(info, 'page_code')

      // 创建新的 item 对象以保持响应性
      const newItem = { ...props.item }
      newItem.data_dync = { ...newItem.data_dync, page_code }
      emit('update:item', newItem)

      await loadFormData()
    }
  })
}

// 生命周期钩子
onMounted(() => {
  init()
  loadFormData()
})

// Watchers
watch(
  () => props.item,
  (newVal) => {
    init()
  },
  { deep: true }
)

watch(
  () => props.item.data_type,
  (val) => {
    if (val === 'dync' || val === 'microapi') {
      loadFormData()
    }
  }
)

watch(
  () => props.item.data_dync,
  () => {
    loadFormData()
  },
  { deep: true }
)
</script>
